<template>
  <div style="display: flex; flex-direction: column; height: 100%; flex: 1;">
    <TableWidget ref="refHiTable" :pagination="pagination" :columns="columns" :load="loadGroupsOfRealm"
                 :has-select="true" :hide-pageable="true" :selected="selectedGrps" style="flex: 1">
      <template v-slot:toolHeader>
        <TableSearchWidget ref="refSearch" :search="searchItems">
          <template v-slot:searchHead>
            <div
                style="display: flex;flex-direction: row; align-items: center; color: #606266; font-size: 13px;margin-right: 8px;">
              <div style="width: 60px; margin-right: 4px;">领域名称</div>
              <el-input type="text" readonly v-model="currRealm.realmName" style="width: 280px; "/>
              <el-tooltip
                  v-if="true"
                  effect="dark"
                  content="选择领域"
                  placement="top">
                <el-dropdown trigger="click" @command="handleRealmCmd">
                  <el-button style="margin: 4px 16px 4px 8px;padding: 0 16px;" icon="MoreFilled" plain round/>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-for="(item) in realmList" :key="item.id" :command="item.id">
                        {{ item.realmName }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>

              </el-tooltip>
              <el-button type="primary" @click="saveGroupsOfPlatform">
                保存
              </el-button>
              <el-button type="danger" @click="onCancel">
                取消
              </el-button>
            </div>
          </template>
        </TableSearchWidget>
      </template>
      <template v-slot:actionBefore>
        <slot name="actionBefore"/>
      </template>
    </TableWidget>
  </div>
</template>

<script setup lang="ts">
import {ElMessageBox} from 'element-plus'
import {onMounted, ref, toRaw} from "vue";
import {msgError, msgInfo} from "@/utils/InfoUtil";
import {useCurrent} from "@/utils/UseCurrentFunc";
import {currentNames} from "@/stores/conf";
import {
  lookupRealm,
  loadRealmByPage,
  loadRealmUserGroupOfPlatformList,
  loadRealmUserGroupOfRealmList,
  realmSaveGroupsOfPlatform
} from "@/apis";
import {useStore} from "@/stores";
import TableSearchWidget from "@/widget/TableSearchWidget.vue";
import TableWidget from "@/widget/TableWidget.vue";

const store = useStore();

const refHiTable = ref();
const refSearch = ref();

const realmList = ref([])
const currRealm = ref({});
const searchItems = ref([]);
const selectedGrps = ref([]);

const {updateCurrent} = useCurrent(currentNames.PLAT_REALM_USER);

withDefaults(defineProps<{
  fromDetail?: boolean,
  addGroup?: any,
  removeGroup?: any,
  loadUserGroup?: any,
  loadAssignGroup?: any,
}>(), {});

const refreshCurrentRealm = async (realmId: string) => {
  currRealm.value = {};

  if (realmId) {
    const realmInfo = await lookupRealm({
      id: realmId,
    });

    if (realmInfo && realmInfo.data) {
      currRealm.value = {
        id: realmInfo.data.id,
        realmName: realmInfo.data.realmName
      }
    }
  }
}

const handleRealmCmd = async (command: string) => {
  if (command == currRealm.value.id) {
    return;
  }

  ElMessageBox.confirm(
      '是否确认更改平台所属领域（此操作会删除已分配给用户的资源信息，请谨慎操作！）?',
      '温馨提示',
      {
        confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
  }).then(async () => {
    const currentPl: any = store.getCurrentPlatform();
    currentPl.realmId = command;
    await doSaveGroupsOfPlatform([]);
    await refreshCurrentRealm(command);
    await refresh();
  })
}

const onCancel = async () => {
  await refresh();
}

const doSaveGroupsOfPlatform = async (selGroups: any) => {
  const currentPl: any = store.getCurrentPlatform();
  const idList = selGroups.map((e: any) => e.id)

  const result: any = await realmSaveGroupsOfPlatform({
    realmId: currentPl.realmId,
    platformId: currentPl.id,
    groups: idList,
  });
  if (result && result.code === 0) {
    msgInfo('保存分配平台分组信息成功!');
  } else {
    msgError(result ? result.message : '保存分配平台分组信息失败！');
  }
}

const saveGroupsOfPlatform = async () => {
  ElMessageBox.confirm(
      '是否确认保存分配给平台的领域分组?',
      '温馨提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
  ).then(async () => {
    const selGroups = refHiTable.value?.getSelectItems();
    await doSaveGroupsOfPlatform(selGroups);
  })
}

const loadRealms = async () => {
  const result: any = await loadRealmByPage({
    current: 1,
    pageSize: 50
  });
  if (result && result.data && result.data.data) {
    realmList.value = result.data.data || [];
  } else {
    realmList.value = [];
  }
}

const loadGroupsOfPlatform = async (data: any, platformId: string) => {
  const result = await loadRealmUserGroupOfPlatformList({
    platformId: platformId
  });

  if (result && result.code === 0) {
    selectedGrps.value = result.data || [];
    msgInfo('加载分配平台分组信息成功!');
  } else {
    selectedGrps.value = [];
    msgError(result ? result.message : '加载分配平台分组信息失败！');
  }

  const selData: any = [];
  const idList = selectedGrps.value.map((e: any) => e.id);
  data.forEach((row: any) => {
    if (idList.includes(row.id)) {
      selData.push(row);
    }
  })

  refHiTable.value?.setSelectItems(selData);

  return result;
}

const doLoadGroupsOfRealm = async (cb: any) => {
  const currentPl: any = toRaw(store.getCurrentPlatform());
  const result = await loadRealmUserGroupOfRealmList({
    realmId: currentPl.realmId
  });

  if (result && result.data) {
    if (cb) {
      await cb(result.data, currentPl.id);
    }
    return {
      code: 0,
      data: {
        current: 1,
        count: result.data.length,
        total: result.data.length,
        data: result.data,
      }
    }
  } else {
    return {
      code: 0,
      data: {
        current: 1,
        count: 0,
        total: 0,
        data: [],
      }
    }
  }
}

const loadGroupsOfRealm = async () => {
  await loadRealms();
  return doLoadGroupsOfRealm(loadGroupsOfPlatform)
}

const refresh = async () => {
  await refHiTable.value?.refreshData({
    ...refSearch.value?.getSearchParams()
  });
}

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const columns = ref([
  {
    id: 'name',
    name: '分组名称',
    show: true,
    action: (data: any, row: any) => {
      updateCurrent({...row})
    }
  },
  {
    id: 'id',
    name: '分组ID',
    hideCol: true,
    show: true,
    canEdit: false,
  },
  {
    id: 'createTime',
    name: '创建时间',
    show: true,
    canEdit: false,
  },
]);

onMounted(() => {
  const currentPl: any = toRaw(store.getCurrentPlatform());
  refreshCurrentRealm(currentPl.realmId);
})

defineExpose({
  refresh,
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

</style>
